package com.atguigu.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public List<Category> findOneCategory() {
        //从Redis缓存中查询所有一级分类数据
        String categoryListJSON = redisTemplate.opsForValue().get("category:one");
        if(StringUtils.hasText(categoryListJSON)){
            List<Category> categoryList= JSON.parseArray(categoryListJSON);
            log.info("从Redis缓存中查询到了所有的一级分类数据");
            return categoryList;
        }
        List<Category> categoryList = categoryMapper.selectOneCategory();
        log.info("从数据库中查询到了所有的一级分类数据");
        redisTemplate.opsForValue().set("category:one" , JSON.toJSONString(categoryList) , 7 , TimeUnit.DAYS);
        return categoryList ;
    }


    /*@Override

    public List<Category> findOneCategory() {
        return categoryMapper.selectOneCategory();
    }*/

    @Override
    @Cacheable(value = "category",key = "'all'")
    public List<Category> findCategoryTree() {
        List<Category> categoryList=categoryMapper.selectAll();
        for (Category category : categoryList) {
            category.setChildren(new ArrayList<>());
        }

        List<Category> oneCategoryList=new ArrayList<>();


        for (Category category : categoryList) {
            if (category.getParentId().intValue()==0){
                oneCategoryList.add(category);
            }else {
                for (Category category1 : categoryList) {
                    if (category1.getId()==category.getParentId()){
                        category1.getChildren().add(category);
                    }
                }
            }
        }

        return oneCategoryList;
    }
}
